<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>3.深拷贝</title>
</head>

<body>
  <!-- 3.深拷贝 -->
  <script>
    var obj = {
      name: 'zhangsan',
      age: 23,
      child: {
        name: 'lisi',
        age: 11,
        child: {
          name: 'wangwu',
          age: 3
        }
      },
      cars: ['TOyota', 'Benz']
    }
    // function deepClone(obj, cloneObj) {
    //   cloneObj = cloneObj || {}

    //   for (let key in obj) {
    //     if (typeof obj[key] === 'object' && obj[key] !== null) {
    //       Object.prototype.toString.call(obj[key]) === '[object Array]' ? cloneObj[key] = [] : cloneObj[key] = {}
    //         deepClone(obj[key], cloneObj[key])
    //     } else {
    //       cloneObj[key] = obj[key]
    //     }
    //   }
    //   return cloneObj
    // }

    function deepClone(obj = {}) {
      if (typeof obj !== 'object' || obj == null) {
        return obj
      }

      let result
      if (obj instanceof Array) {
        result = []
      } else {
        result = {}
      }

      for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
          result[key] = deepClone(obj[key])
        }
      }

      return result
    }
    let obj2 = {}
    obj2 = deepClone(obj, obj2)
    obj.cars.push('HHH')
    console.log(obj2);
  </script>
</body>

</html>